<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- Card -->
    <el-card>

      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        :closable="false"
        center
      >
      </el-alert>

      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeSteps - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属相"></el-step>
        <el-step title="商品图像"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <!-- tab 栏区域 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeSteps"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item
              label="商品名称："
              prop="shopName"
            >
              <el-input v-model="addForm.shopName"></el-input>
            </el-form-item>

            <el-form-item
              label="商品价格："
              prop="shopPrice"
            >
              <el-input v-model="addForm.shopPrice" type="number"></el-input>
            </el-form-item>

            <el-form-item
              label="商品重量："
              prop="shopWeight"
            >
              <el-input v-model="addForm.shopWeight" type="number"></el-input>
            </el-form-item>

            <el-form-item
              label="商品数量："
              prop="shopNumber"
            >
              <el-input v-model="addForm.shopNumber" type="number"></el-input>
            </el-form-item>

            <el-form-item
              label="商品分类："
              prop="shopTypeArray"
            >
              <el-cascader
                clearable
                v-model="addForm.shopTypeArray"
                :options="shopTypeList"
                :props="cascaderProps"
                @change="handleCascaderChange"
                ref="shopTypeRef"
              >
              </el-cascader>
            </el-form-item>

          </el-tab-pane>

          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单的 Item 项 -->
            <el-form-item :label="item.shopParamsName" v-for="item in dynamicTableData" :key="item.shopParamsId">
              <el-checkbox-group v-model="item.shopParamsValue">
                <el-checkbox :label="cb" v-for="(cb,i) in item.shopParamsValue" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in staticTableData"
              :label="item.shopParamsName"
              :key="item.shopParamsId"
            >
              <el-input v-model="item.shopParamsValue"/>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片上传的后台Api地址 -->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="handleHeaders"

              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-tab-pane>

          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor
              ref="myQuillEditor"
              v-model="addForm.shopIntroduce"

            />
            <!-- 添加商品的按钮 -->
            <el-button
              type="primary"
              class="addShopButton"
              @click="addShopClick"
            > 添加商品</el-button>

          </el-tab-pane>
        </el-tabs>

      </el-form>


      <!-- 图片预览 -->
      <el-dialog
        title=" 图片预览"
        :visible.sync="pictureShowDialogVisible"
        width="50%"
      >
        <img :src="picturePath" alt="图片预览" class="prevImage">
      </el-dialog>

    </el-card>


  </div>
</template>

<script>
import _ from 'lodash'

export default {
  name: "Add",
  data() {
    return {
      // 步骤，激活第几步
      activeSteps: '0',
      // 添加商品的表单数据对象
      addForm: {
        shopName: '',
        shopPrice: 0,
        shopWeight: 0,
        shopNumber: 0,
        // 商品分类数组
        shopTypeArray: [],
        // 图片数组
        shopPicture: [],
        // 商品介绍
        shopIntroduce: '',
        shopParams: []
      },
      // 新增，表单验证
      addFormRules: {
        shopName: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        shopPrice: [
          {required: true, message: '请输入商品价格', trigger: 'blur'}
        ],
        shopWeight: [
          {required: true, message: '请输入商品重量', trigger: 'blur'}
        ],
        shopNumber: [
          {required: true, message: '请输入商品数量', trigger: 'blur'}
        ],
        shopTypeArray: [
          {required: true, message: '请选择商品分类', trigger: 'blur'}
        ]
      },
      // 商品分类 list
      shopTypeList: [],
      // 级联，属性配置
      cascaderProps: {
        label: 'shopTypeName',
        value: 'shopTypeId',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      // 动态参数
      dynamicTableData: [],
      // 静态属性
      staticTableData: [],
      // 上传图片的Url地址
      uploadUrl: 'http://127.0.0.1:8081/shop/uploadImage',
      // 图片上床组件的headers请求头
      handleHeaders: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片，预览路径
      picturePath: '',
      // 图片，预览
      pictureShowDialogVisible: false

      // ----- data end -----
    }
  },
  created() {
    this.getShopTypeList();
  },
  methods: {
    // 商品分类,获取列表
    async getShopTypeList() {
      const {data: res} = await this.$http.get(`/shopType/getShopTypeList/tree`);
      if (!res.status) return this.$message.error(res.message);
      this.shopTypeList = this.getTreeData(res.data.shopTypeMapListTree);
    },
    // 级联， 改变事件
    handleCascaderChange() {
      if (this.addForm.shopTypeArray.length !== 3) {
        this.addForm.shopTypeArray = [];
        this.$refs.shopTypeRef.dropDownVisible = false;
      }
      this.$refs.shopTypeRef.dropDownVisible = false;
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // tab，切换前调用
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.shopTypeArray.length !== 3) {
        this.$message.error("请先选择三级商品分类");
        return false;
      }
    },
    // tab 被点击
    tabClick() {

      if (this.activeSteps === '1') {
        // 访问动态参数面板
        this.getShopParamsList('dynamic');
      } else if (this.activeSteps === '2') {
        // 访问静态属性面板
        this.getShopParamsList('static');
      }
    },
    // 商品参数，获取
    async getShopParamsList(type) {
      const {data: res} = await this.$http({
        url: `/shopParams/getShopParamsList`,
        method: `get`,
        params: {'id': this.shopTypeId, 'type': type}
      });
      if (!res.status) return this.$message.error(res.message);

      if (type === 'dynamic') {
        res.data.shopParamsList.forEach(item => {
          item.shopParamsValue = item.shopParamsValue ? item.shopParamsValue.split(' ') : [];
        })
        this.dynamicTableData = res.data.shopParamsList;
      } else {
        this.staticTableData = res.data.shopParamsList;
      }
    },
    // 上传图片，
    handlePreview(file) {
      console.log(",,handlePreview", file);
      this.picturePath = file.response.data.path;
      console.log(",,handlePreview", file);
      this.pictureShowDialogVisible = true;
    },
    handleRemove(file) {
      console.log(",,handleRemove", file);
      //1. 获取将要删除的图片的路径
      const filePath = file.response.data.path
      //2. 从pictureInfo数组中。找到这个图片对应的索引值
      const i = this.addForm.shopPicture.findIndex(x => x.path === filePath)
      //3. 调用数组的 splice 方法，把图片信息对象，从pictureInfo 数组中移除
      this.addForm.shopPicture.splice(i, 1);
      console.log("===,", this.addForm);

    },

    // 图片，上传成功的事件
    handleSuccess(response) {
      console.log("handleSuccess", response);
      //1. 拼接得到一个图片信息对象
      const picturePath = {shopPicturePath: response.data.path};
      //2. 将图片信息对象 push 到 pictureInfo 数组中
      this.addForm.shopPicture.push(picturePath);

      console.log("pictureInfo=", this.addForm);

    },
    // 添加商品点击事件
    addShopClick() {
      this.$refs.addFormRef.validate(async valid => {
        if(!valid) return this.$message.error("校验失败！");

        // 与下面用一种就好
        const form = _.cloneDeep(this.addForm);
        // let addFormData = {}
        // Object.assign(addFormData, this.addForm);

        // 商品分类
        form.shopType = form.shopTypeArray.join(',');
        // 提交前把商品价格改为两部分
        const price = (form.shopPrice + '').split('.');
        form.shopPriceInt = price[0];
        form.shopPriceDouble = price[1];
        // 处理动态参数
        // this.dynamicTableData.forEach(item => {
        //   const newInfo = {'shopParamsId': item.shopParamsId,
        //   'shopParamsValue': item.shopParamsValue.join(' ')
        //   };
        //   form.shopParams.push(newInfo);
        // });
        // // 处理静态属性
        // this.staticTableData.forEach(item => {
        //   const newInfo = {'shopParamsId': item.shopParamsId,
        //     'shopParamsValue': item.shopParamsValue
        //   };
        //   form.shopParams.push(newInfo);
        // });
        this.dynamicTableData.forEach(item => {
          let item2 = _.cloneDeep(item);
          item2.shopParamsValue.join(' ');
          form.shopParams.push(item2);
        });
        this.staticTableData.forEach(item => {
          form.shopParams.push(item);
        });

        const {data:res} = await this.$http({
          url: `/shop/addShop`,
          method: 'post',
          data: form
        });
        if (!res.status) return this.$message.error(res.message);
        this.$message.success(res.message);
      });
    }
    // ----- method end -----
  },
  computed: {
    shopTypeId() {
      if (this.addForm.shopTypeArray.length === 3) return this.addForm.shopTypeArray[2];
      return null;
    }
  }

}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}

.prevImage {
  width: 100%;
}
.addShopButton{
  margin-top: 15px;
}
</style>
